<template>
  <div class="room-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">房间/队伍管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddRoom">
          <el-icon><Plus /></el-icon>
          创建房间
        </el-button>
        <el-button type="danger" @click="handleDeleteSelectedRooms" :disabled="selectedRooms.length === 0">
          删除选中房间
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <el-input 
        v-model="searchKeyword" 
        placeholder="搜索房间名称/ID" 
        prefix-icon="Search"
        class="search-input"
        @keyup.enter="handleSearch"
      />
      <el-select v-model="statusFilter" placeholder="房间状态" class="filter-select">
        <el-option label="全部" value="" />
        <el-option label="活跃" value="active" />
        <el-option label="已关闭" value="closed" />
      </el-select>
      <el-select v-model="typeFilter" placeholder="房间类型" class="filter-select">
        <el-option label="全部" value="" />
        <el-option label="公开" value="public" />
        <el-option label="私有" value="private" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetFilters">重置</el-button>
    </div>

    <!-- 房间表格 -->
    <el-table 
      v-loading="loading" 
      :data="roomsData" 
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="房间ID" width="150" sortable />
      <el-table-column prop="name" label="房间名称" sortable>
        <template #default="scope">
          <div class="room-name">
            <el-avatar :src="scope.row.avatar" class="room-avatar" />
            <span>{{ scope.row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="owner" label="创建者" width="120" sortable>
        <template #default="scope">
          <div class="owner-info">
            <el-avatar :src="scope.row.owner.avatar" class="owner-avatar" />
            <span>{{ scope.row.owner.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="房间类型" width="100" sortable>
        <template #default="scope">
          <el-tag :type="getRoomTypeTagType(scope.row.type)">
            {{ scope.row.type === 'public' ? '公开' : '私有' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="memberCount" label="成员数量" width="100" sortable />
      <el-table-column prop="messageCount" label="消息数量" width="100" sortable />
      <el-table-column prop="status" label="房间状态" width="100" sortable>
        <template #default="scope">
          <el-switch 
            v-model="scope.row.status" 
            :active-value="'active'" 
            :inactive-value="'closed'"
            @change="handleStatusChange(scope.row.id, $event)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="lastActivityTime" label="最后活动时间" sortable>
        <template #default="scope">
          {{ formatTime(scope.row.lastActivityTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" sortable>
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleViewRoom(scope.row)">
            查看详情
          </el-button>
          <el-button type="primary" link @click="handleEditRoom(scope.row)">
            编辑
          </el-button>
          <el-button 
            type="danger" 
            link 
            @click="handleDeleteRoom(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRooms"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑房间对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form 
        ref="roomFormRef" 
        :model="roomForm" 
        :rules="roomRules" 
        label-width="100px"
      >
        <el-form-item label="房间名称" prop="name">
          <el-input v-model="roomForm.name" placeholder="请输入房间名称" />
        </el-form-item>
        <el-form-item label="房间类型" prop="type">
          <el-select v-model="roomForm.type" placeholder="请选择房间类型">
            <el-option label="公开" value="public" />
            <el-option label="私有" value="private" />
          </el-select>
        </el-form-item>
        <el-form-item label="房间描述" prop="description">
          <el-input v-model="roomForm.description" type="textarea" placeholder="请输入房间描述" :rows="3" />
        </el-form-item>
        <el-form-item label="房间状态" prop="status">
          <el-switch 
            v-model="roomForm.status" 
            :active-value="'active'" 
            :inactive-value="'closed'"
            active-text="活跃" 
            inactive-text="关闭"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitRoom">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'

// 表格数据
const rooms = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalRooms = ref(0)
const selectedRooms = ref([])

// 搜索和筛选条件
const searchKeyword = ref('')
const statusFilter = ref('')
const typeFilter = ref('')

// 对话框相关
const dialogVisible = ref(false)
const editingRoomId = ref(null)
const dialogTitle = computed(() => editingRoomId.value ? '编辑房间' : '创建房间')
const roomFormRef = ref(null)

// 房间表单数据
const roomForm = reactive({
  name: '',
  type: 'public',
  description: '',
  status: 'active'
})

// 表单验证规则
const roomRules = reactive({
  name: [
    { required: true, message: '请输入房间名称', trigger: 'blur' },
    { min: 2, max: 30, message: '房间名称长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择房间类型', trigger: 'change' }
  ],
  description: [
    { max: 200, message: '房间描述不能超过 200 个字符', trigger: 'blur' }
  ]
})

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 根据房间类型获取标签类型
const getRoomTypeTagType = (type) => {
  return type === 'public' ? 'success' : 'primary'
}

// 过滤后的房间数据
const roomsData = computed(() => {
  let filtered = [...rooms.value]
  
  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(room => 
      room.name.toLowerCase().includes(keyword) ||
      room.id.toLowerCase().includes(keyword)
    )
  }
  
  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(room => room.status === statusFilter.value)
  }
  
  // 类型过滤
  if (typeFilter.value) {
    filtered = filtered.filter(room => room.type === typeFilter.value)
  }
  
  // 更新总数
  totalRooms.value = filtered.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 模拟加载房间数据
const loadRoomsData = () => {
  loading.value = true
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 生成一些模拟用户数据（房间创建者）
    const mockOwners = Array.from({ length: 8 }, (_, i) => ({
      id: `user${i + 1}`,
      username: `admin${i + 1}`,
      avatar: `https://api.dicebear.com/9.x/avataaars/svg?seed=admin${i + 1}`
    }))
    
    // 房间名称列表
    const roomNames = [
      '技术讨论组', '产品规划小组', '设计团队', '市场部交流群',
      '研发中心', 'UI设计交流', '前端开发组', '后端技术群',
      '测试团队', '项目管理组', '运营团队', '销售交流群',
      '人力资源部', '财务共享中心', '客服支持组', '高管会议群'
    ]
    
    // 生成一些模拟房间数据
    const mockRooms = Array.from({ length: 40 }, (_, i) => {
      const owner = mockOwners[Math.floor(Math.random() * mockOwners.length)]
      const isPublic = Math.random() > 0.3
      
      return {
        id: `room_${1000 + i}`,
        name: roomNames[i % roomNames.length] + (i >= roomNames.length ? `(${i % roomNames.length + 1})` : ''),
        avatar: `https://picsum.photos/40/40?random=${i}`,
        owner: owner,
        type: isPublic ? 'public' : 'private',
        description: isPublic ? '欢迎加入讨论！' : '私有团队交流空间',
        memberCount: Math.floor(Math.random() * 50) + 5,
        messageCount: Math.floor(Math.random() * 5000) + 100,
        status: Math.random() > 0.1 ? 'active' : 'closed',
        lastActivityTime: new Date(Date.now() - Math.random() * 24 * 60 * 60 * 1000).toISOString(),
        createTime: new Date(Date.now() - Math.random() * 90 * 24 * 60 * 60 * 1000).toISOString()
      }
    })
    
    rooms.value = mockRooms
    loading.value = false
  }, 500)
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置筛选条件
const resetFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  typeFilter.value = ''
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 选择房间变化
const handleSelectionChange = (selection) => {
  selectedRooms.value = selection
}

// 打开添加房间对话框
const handleAddRoom = () => {
  editingRoomId.value = null
  // 重置表单
  Object.assign(roomForm, {
    name: '',
    type: 'public',
    description: '',
    status: 'active'
  })
  dialogVisible.value = true
}

// 打开编辑房间对话框
const handleEditRoom = (room) => {
  editingRoomId.value = room.id
  // 填充表单数据
  Object.assign(roomForm, {
    name: room.name,
    type: room.type,
    description: room.description,
    status: room.status
  })
  dialogVisible.value = true
}

// 提交房间表单
const handleSubmitRoom = async () => {
  try {
    // 验证表单
    await roomFormRef.value.validate()
    
    loading.value = true
    
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    if (editingRoomId.value) {
      // 编辑房间
      const index = rooms.value.findIndex(room => room.id === editingRoomId.value)
      if (index !== -1) {
        rooms.value[index] = {
          ...rooms.value[index],
          name: roomForm.name,
          type: roomForm.type,
          description: roomForm.description,
          status: roomForm.status
        }
      }
      ElMessage.success('房间信息更新成功')
    } else {
      // 添加房间
      const currentUser = {
        id: 'current_user',
        username: '当前用户',
        avatar: 'https://api.dicebear.com/9.x/avataaars/svg?seed=currentuser'
      }
      
      const newRoom = {
        id: `room_${Date.now()}`,
        name: roomForm.name,
        avatar: `https://picsum.photos/40/40?random=${Date.now()}`,
        owner: currentUser,
        type: roomForm.type,
        description: roomForm.description,
        memberCount: 1, // 创建者自己算一个成员
        messageCount: 0,
        status: roomForm.status,
        lastActivityTime: new Date().toISOString(),
        createTime: new Date().toISOString()
      }
      rooms.value.unshift(newRoom)
      ElMessage.success('房间创建成功')
    }
    
    // 关闭对话框
    dialogVisible.value = false
    
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 查看房间详情
const handleViewRoom = (room) => {
  ElMessage.info(`查看房间 ${room.name} 的详情`)
}

// 删除单个房间
const handleDeleteRoom = (roomId) => {
  ElMessageBox.confirm(
    '确定要删除这个房间吗？此操作不可撤销，将同时删除房间内的所有消息记录。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      loading.value = true
      
      // 模拟API请求延迟
      setTimeout(() => {
        const index = rooms.value.findIndex(room => room.id === roomId)
        if (index !== -1) {
          rooms.value.splice(index, 1)
        }
        ElMessage.success('房间已删除')
        loading.value = false
      }, 500)
    })
    .catch(() => {
      ElMessage.info('已取消删除操作')
    })
}

// 批量删除房间
const handleDeleteSelectedRooms = () => {
  if (selectedRooms.value.length === 0) {
    ElMessage.warning('请先选择要删除的房间')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRooms.value.length} 个房间吗？此操作不可撤销，将同时删除房间内的所有消息记录。`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      loading.value = true
      
      // 模拟API请求延迟
      setTimeout(() => {
        const selectedIds = selectedRooms.value.map(room => room.id)
        rooms.value = rooms.value.filter(room => !selectedIds.includes(room.id))
        selectedRooms.value = []
        ElMessage.success(`已成功删除 ${selectedIds.length} 个房间`)
        loading.value = false
      }, 500)
    })
    .catch(() => {
      ElMessage.info('已取消批量删除操作')
    })
}

// 修改房间状态
const handleStatusChange = (roomId, newStatus) => {
  loading.value = true
  
  // 模拟API请求延迟
  setTimeout(() => {
    const room = rooms.value.find(r => r.id === roomId)
    if (room) {
      room.status = newStatus
      ElMessage.success(`房间状态已更新为${newStatus === 'active' ? '活跃' : '关闭'}`)
    }
    loading.value = false
  }, 300)
}

// 页面加载时初始化数据
onMounted(() => {
  loadRoomsData()
})
</script>

<style scoped>
.room-management {
  width: 100%;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 搜索和筛选区域 */
.search-filter-section {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 120px;
}

/* 房间名称样式 */
.room-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.room-avatar {
  width: 32px;
  height: 32px;
}

/* 创建者信息样式 */
.owner-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.owner-avatar {
  width: 24px;
  height: 24px;
}

/* 分页区域 */
.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .search-input {
    width: 200px;
  }
  
  .filter-select {
    width: 100px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .search-filter-section {
    flex-direction: column;
  }
  
  .search-input,
  .filter-select {
    width: 100%;
  }
}
</style>